package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.util.Cart;
import org.petstore.util.CartItem;
import org.petstore.service.CartService;
import org.petstore.service.CatalogService;
import org.petstore.web.servlet.util.MyUtil;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartsServlet extends HttpServlet {

    String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    String LOGIN_HTML = "/WEB-INF/jsp/account/SignOnForm.jsp";

    private final CatalogService catalogService = MyUtil.getApplicationContext().getBean("catalogService", CatalogService.class);
    private final CartService cartService = MyUtil.getApplicationContext().getBean("cartService", CartService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //要添加的itemId
        String workingItemId = request.getParameter("workingItemId");

        HttpSession session = request.getSession();
        Account loginUser = (Account) session.getAttribute("loginUser");

        if (loginUser == null) {
            request.setAttribute("msg", "请先登录");
            request.getRequestDispatcher(LOGIN_HTML).forward(request, response);
            return;
        }

        //CartItem 可以实现添加n个该商品
        CartItem cartItem = new CartItem();
        cartItem.setItem(catalogService.getItem(workingItemId));
        cartItem.setQuantity(1);
        cartItem.setInStock(true);
        cartService.addIntoCart(loginUser.getUsername(), cartItem);

        //重新获取购物车
        Cart cart = cartService.getCartByName(loginUser.getUsername());

        session.setAttribute("cart", cart);
        request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }
}
